#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

#define STACK_SIZE (1024 * 1024) // 1MB 的栈空间
    // ⼦进程执⾏的函数

static int child_func(void *arg)
{
    while(1)
    {
         printf("Child process: PID = %d\n", getpid());
         sleep(1);
    }
    return 0;
}


int main()
{
    char *stack = (char *)malloc(STACK_SIZE); // 为⼦进程分配栈空间
    if (stack == NULL)
    {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    // 使⽤ clone 创建⼦进程
    pid_t pid = clone(child_func, stack + STACK_SIZE, CLONE_VM | SIGCHLD,NULL);

    if (pid == -1)
    {
        perror("clone");
        free(stack);
        exit(EXIT_FAILURE);
    }
    printf("Parent process: PID = %d, Child PID = %d\n", getpid(), pid);
    // 等待⼦进程结束
    if (waitpid(pid, NULL, 0) == -1)
    {
        perror("waitpid");
        free(stack);
        exit(EXIT_FAILURE);
    }
    free(stack);
    return 0;
}